/**
 * @(#)ApkSimulatorTimer.java 2017年03月25日
 * Copyright(C) 2016 ZHEXIN IT CO.,LTD. All rights reserved.
 */
package org.jsbd.boss.timer;

import org.jsbd.boss.common.BaseThread;
import org.jsbd.boss.common.redis.RedisClient;
import org.jsbd.boss.domian.DaylimitBean;
import org.jsbd.boss.domian.channel.ChannelApkConfig;
import org.jsbd.boss.service.IDaylimitService;
import org.jsbd.boss.util.CacheKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * 日限更新定时器
 * 
 * @author <a href="mailto:wangjunbiao@zhexinit.com" >王俊标</a>
 * @version 1.0.0
 */
public class MarkDaylimitTimer extends BaseThread {
	public static final Logger LOGGER = LoggerFactory.getLogger(MarkDaylimitTimer.class);

	@Autowired
	private IDaylimitService daylimitService;
	@Autowired
	private RedisClient redisClient;




	@Override
	public void start() {
		LOGGER.info("mark daylimit update start");
		try {
			if (redisClient.evalSetNx(CacheKey.MARK_DAYLIMIT_LOCK_KEY, 6000)) {
				List<DaylimitBean> daylimitBeans = daylimitService.findDeltaData(50);
				List<ChannelApkConfig> channelApkConfigs = new ArrayList<ChannelApkConfig>();
				for (DaylimitBean daylimitBean : daylimitBeans) {
					ChannelApkConfig channelApkConfig = new ChannelApkConfig();
					channelApkConfig.setMark(daylimitBean.getMark());
					channelApkConfig.setDaylimit(daylimitBean.getDaylimit());
					channelApkConfigs.add(channelApkConfig);
				}
				
				if (!channelApkConfigs.isEmpty()) {
					daylimitService.updateDaylimit(channelApkConfigs, daylimitBeans);
				}
			}
		} catch (Exception e) {
			LOGGER.error("更新日限异常", e);
		} finally {
			redisClient.remove(CacheKey.MARK_DAYLIMIT_LOCK_KEY);
		}
	}
}
